package com.bdqn.schoolcms.config.handler;

import com.bdqn.schoolcms.vo.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <功能简要><br>
 * <>
 *
 * @author ：yjw
 * @date ：Created in 2021/4/7 10:34
 * @description：全局异常处理
 * @modified By：
 * @version: 1.0.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 当系统出现MethodArgumentNotValidException这个异常时，会调用下面的方法
     * MethodArgumentNotValidException如果页面传参是json对象 |json对象为空的话会抛出这个异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R jsonErrorHandler(MethodArgumentNotValidException e){
        return getAjaxResult(e.getBindingResult());
    }
    @ExceptionHandler(value = BindException.class)
    public R queryErrorHandler(BindException e){
        return getAjaxResult(e.getBindingResult());
    }

    private R getAjaxResult(BindingResult bindingResult) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError allError : allErrors) {
            Map<String, Object> map = new HashMap<>();
            map.put("defaultMessage", allError.getDefaultMessage());
            map.put("objectName", allError.getObjectName());
            //注意，这里面拿到具体的某一个属性
            FieldError fieldError = (FieldError) allError;
            map.put("field", fieldError.getField());
            list.add(map);
        }

        return R.fail("后端数据校验异常", list);
    }



}
